package com.starblink.library.widget.subscription

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.isEmail
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.ext.toastError
import com.starblink.android.basic.ext.toastSuccess
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.basic.apollo.ext.optional
import com.starblink.rocketreserver.FetchAccountInfoQuery
import com.starblink.rocketreserver.FetchSubscriptionSettingQuery
import com.starblink.rocketreserver.ModifySubscriptionSettingMutation
import com.starblink.rocketreserver.type.SubscriptionSettingReq
import kotlinx.coroutines.launch

/**
 *  Create by yuanl at 2023/10/8
 **/
class SubsVM: BaseViewModel() {

    val bindEmailLD = MutableLiveData<Boolean>()

    val loadEmailLD = MutableLiveData<String?>()

    fun loadAccountInfo() {
        viewModelScope.launch {
            SkGqlClient.skQuery(
                FetchAccountInfoQuery(
                ),
                showDefaultLoading = false
            )?.data?.fetchAccountInfo?.let {
                UserDataCenter.setAccountInfo(it)
            }
        }
    }


    fun bindSubsEmail(email: String) {
        //toast(email)
        if (!email.isEmail()) {
            toastError("Your Email Format Is Incorrect")
            return
        }
        viewModelScope.launch {
            SkGqlClient.skMutation(ModifySubscriptionSettingMutation(
                req = SubscriptionSettingReq(
                    email = email.optional()
                )
            ))?.run {
                if (data?.modifySubscriptionSetting == true) {
                    toastSuccess("Email Set Successfully")
                    bindEmailLD.postValue(true)
                } else {
                    toastError(errors?.firstOrNull()?.message)
                }
            }
        }
    }

    fun fetchSubsEmail() {
        viewModelScope.launch {
            SkGqlClient.skQuery(
                FetchSubscriptionSettingQuery(),
                showDefaultLoading = true
            )?.data?.fetchSubscriptionSetting?.subscriptionSettingRespF?.let {
                loadEmailLD.postValue(it.email.orEmpty().ifEmpty { it.registerEmail })
            }
        }
    }

}